package cn.xorange.commons.core.auth.handler;

import cn.xorange.commons.security.configuration.SecurityProperties;
import cn.xorange.commons.security.constants.SecurityConstants;
import cn.xorange.commons.security.entity.SecurityUser;
import cn.xorange.commons.security.enums.LoginType;
import cn.xorange.commons.security.enums.SysType;
import cn.xorange.commons.security.exception.SecurityException;
import cn.xorange.commons.security.mapper.LoginUserMapper;
import cn.xorange.commons.security.service.LoginHandler;
import cn.xorange.commons.utils.cache.ICacheService;
import cn.xorange.commons.core.constants.SysConstants;
import cn.xorange.commons.utils.thirdApp.WeChatUtils;
import cn.xorange.commons.utils.thirdApp.entity.WxSession;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @author : yangjian
 * date : 2024/2/5
 * description :
 */
public class AppMpLoginHandler implements LoginHandler {
    @Resource
    LoginUserMapper userMapper;
    @Resource
    ICacheService cacheService;


    @Override
    public SecurityProperties config() {
        SecurityProperties properties = new SecurityProperties();
        properties.setSysType(SysType.APP.type());
        properties.setLoginType(LoginType.WX.type());
        properties.setEnableCaptcha(false);
        properties.setTokenExpire(5 * 24 * 60 * 60L);
        return properties;
    }

    @Override
    public SecurityUser handle(JSONObject object) {
        String code = object.getString(SecurityConstants.LOGIN_NAME);
        String appId = object.getString(SecurityConstants.APP_ID);

        String appIdSecretJson = cacheService.getCacheObject(SysConstants.APPID_SECRET_SYS_DICT_NAME).toString();
        JSONArray array =  JSON.parseArray(appIdSecretJson);
        String secret = null;
        for(Object o : array ){
            JSONObject obj = (JSONObject)o;
            if (obj.getString(SysConstants.DICT_VALUE).equals(appId)){
                secret = obj.getString(SysConstants.DICT_REMARK);
                break;
            }
        }
        if (Objects.isNull(secret)){
            throw SecurityException.systemError("appid密钥对未找到");
        }

        WxSession sessionAndOpenId = WeChatUtils.getSessionAndOpenId(appId, secret, code);
        if(Objects.nonNull(sessionAndOpenId.getOpenid())){
            SecurityUser user = userMapper.selectAppUser(sessionAndOpenId.getOpenid(),LoginType.WX.type());
            if(Objects.isNull(user)){
                boolean isRegister = object.getBoolean(SecurityConstants.LOGIN_REGISTER);
                if(isRegister){
                    SecurityUser regUser = JSON.to(SecurityUser.class,object);

                    regUser.setSysType(SysType.APP);
                    regUser.setOpenId(sessionAndOpenId.getOpenid());
                    regUser.setUnionId(sessionAndOpenId.getUnionid());
                    regUser.setCreateTime(new Date());
                    this.userMapper.registerUser(regUser);
                    user = userMapper.selectAppUser(sessionAndOpenId.getOpenid(),LoginType.WX.type());

                } else {
                    user = new SecurityUser();
                }
            }else {
                // 补填unionId
                if(Objects.nonNull(sessionAndOpenId.getUnionid()) && Objects.isNull(user.getUnionId())){
                    user.setUnionId(sessionAndOpenId.getUnionid());
                    this.userMapper.updateUnionIdByAppUser(sessionAndOpenId.getOpenid(),sessionAndOpenId.getUnionid());
                }
            }
            user.setEnable(SysConstants.FLAG_SUCCESS.equals(user.getStatus()));
            return user;
        }else {
            throw  SecurityException.systemError(sessionAndOpenId.getErrMsg());
        }
    }

    //@Override
    //public TimerTask setLog(String loginName, SecurityUser user, Integer status, String msg) {
    //    LoginLog log = null;
    //    if(Objects.nonNull(loginName) && !loginName.isEmpty()) {
    //        log = new LoginLog(loginName, SecurityConstants.LOGIN_TYPE_WX, status, msg);
    //        if (Objects.nonNull(user)) {
    //            log.setTenantId(user.getTenantId());
    //            log.setTenantName(user.getTenantName());
    //            log.setUserId(user.getUserId());
    //            log.setUserName(user.getUsername());
    //        }
    //    }
    //    LoginLog finalLog = log;
    //    return new TimerTask() {
    //        @Override
    //        public void run() {
    //            if(Objects.nonNull(finalLog)){
    //                logMapper.insertAppLoginLog(finalLog);
    //            }
    //        }
    //    };
    //}
}
